package impl;

import java.util.List;

import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entities.LindenBet;
import entities.LotteryGame;

import api.IGameEngine;

/**
 * Session Bean implementation class GameEngine
 */
@Singleton(name="IGameEngine")
@TransactionAttribute(value=TransactionAttributeType.REQUIRES_NEW)
public class GameEngine implements IGameEngine {

	@PersistenceContext(unitName="LotteryGamePU")
	EntityManager em;
	
	private static int MIN = 1;
	private static int MAX = 100;

	
    /**
     * Default constructor. 
     */
    public GameEngine() {
    }

	@Override
	public boolean makeBet(int sourceAppId, int betNumber, int betAmount,
			int gamblerId, int gameId) {

		System.out.print("*** GAME ENGINE ***");
		
		LotteryGame game = em.find(LotteryGame.class, gameId);		
		
		if(game == null)
			return false;
		
		LindenBet bet = new LindenBet();
		bet.setAppId(sourceAppId);
		bet.setBetNumber(betNumber);
		bet.setLindenEuros(betAmount);
		bet.setLotteryGame(game);
		bet.setUserId(gamblerId);
		em.persist(bet);
		
		
		return true;
	}


	@Override
	public List<LindenBet> getWinnerList(int sourceAppId) {
		
    	System.out.print("*** GAME ENGINE *** getWinnerList");
		
		Query q = em.createNamedQuery("getLotteryAppWinners");
		q.setParameter(1, sourceAppId);
		
		List<LindenBet> winners = q.getResultList();
		
		return winners;
	}
	
	@Schedule(minute="*/1", hour="*", persistent=false)
	private void genWinnerNumber() {
		try {
	    	System.out.print("*** GAME ENGINE *** genWinnerNumber");

			Query query=em.createNamedQuery("getAvailableLotteries");
			
			LotteryGame game = (LotteryGame) query.getSingleResult();		
			
			int number = MIN + (int)(Math.random() * ((MAX - MIN) + 1));
			game.setDrawnNumber(number);
			em.persist(game);
		
		} catch (NoResultException e) {
			System.out.println("*** No lotteries available ***");
			
		}
	}

	@Override
	public LotteryGame getActiveLottery() {
		Query query=em.createNamedQuery("getAvailableLotteries");
		
		LotteryGame game = (LotteryGame) query.getSingleResult();		
		
		return game;
	}
	
	

}
